#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
	int i;
	for(i=0; i<argc; i++){
		printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
	}
	printf("\n");
	return 0;
}

int main(int argc, char **argv){
	sqlite3 *db;
	char *zErrMsg = 0;
	int rc;
	char **pazResult;
	int nRow, nCol;

	rc = sqlite3_open("test.db", &db);
	if( rc ){
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return(1);
	}
	char *sql;
	sql = "select count(*) FROM sqlite_master WHERE type='table' and name='test'";
	rc = sqlite3_get_table(db, sql, &pazResult, &nRow, &nCol, &zErrMsg);
	if(rc != SQLITE_OK)
	{
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
		goto clear;
	}
	int count = atoi(pazResult[1]);
	if(count <= 0)
	{
		sql = "create table test(iInt int, cChar varchar(255))";
		rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
		if( rc!=SQLITE_OK ){
			fprintf(stderr, "SQL error: %s\n", zErrMsg);
			sqlite3_free(zErrMsg);
			goto clear;
		}
	}
	sqlite3_free_table(pazResult);

	sql = "insert into test(iInt, cChar) values(10, 'xyz')";
	rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
	if( rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}
	sql = "select * FROM test";
	rc = sqlite3_get_table(db, sql, &pazResult, &nRow, &nCol, &zErrMsg);
	if(rc != SQLITE_OK)
	{
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
		goto clear;
	}
	for(int i = 0; i < (nRow + 1) * nCol; ++i)
	{
		fprintf(stdout, "%s\n", pazResult[i]);
	}
	sqlite3_free_table(pazResult);
clear:
	sqlite3_close(db);
	return 0;
}